package com.lyk.coursearrange.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lyk.coursearrange.common.ServerResponse;
import com.lyk.coursearrange.common.core.base.code.CodeEnum;
import com.lyk.coursearrange.common.core.base.result.R;
import com.lyk.coursearrange.common.exception.MZException;
import com.lyk.coursearrange.common.log.annotation.Log;
import com.lyk.coursearrange.common.log.enums.OperationType;
import com.lyk.coursearrange.entity.Admin;
import com.lyk.coursearrange.entity.dto.AdminDto;
import com.lyk.coursearrange.entity.request.PasswordVO;
import com.lyk.coursearrange.entity.request.UserLoginRequest;
import com.lyk.coursearrange.service.*;
import com.lyk.coursearrange.service.impl.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lequal
 * @since 2020-03-06
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private PostService postService;
    @Autowired
    private JurisdictionService jurisdictionService;
    @Autowired
    private PostAsJurisdictionService postAsJurisdictionService;
    @Autowired
    private UserAsPostService userAsPostService;







    /**
     * 查询所有用户信息
     * @param
     * @return
     */
    @PostMapping("/userlist")
    @Log(title = "分页查询用户列表", operationType = OperationType.SELECT)
    public R userlist(@RequestBody Map<String,String> param) {
        return R.ok().message("查询用户信息成功")
                .data("list",adminService.userlist(param))
                .data("count",adminService.usercount(param));

    }
    /**
     * 查询所有角色信息
     * @param
     * @return
     */
    @PostMapping("/postlist")
    @Log(title = "查询角色列表", operationType = OperationType.SELECT)
    public R postlist(@RequestBody Map<String,String> param) {
        Long user_id =0L;
        if(param.get("user_id")!=null&&!param.get("user_id").equals("")){
            user_id = Long.valueOf(param.get("user_id"));
        }
        String po_name = null;
        if(param.get("poName")!=null&&!param.get("poName").equals("")){
            po_name = param.get("poName");
        }
        return R.ok().message("查询角色信息成功").data("list",postService.postlist(user_id,po_name));
    }




    /**
     * 查询所有权限信息
     * @param
     * @return
     */
    @PostMapping("/jurisdictionlist")
    @Log(title = "查询权限列表", operationType = OperationType.SELECT)
    public R jurisdictionlist(@RequestBody Map<String,String> param) {
        Long po_id =0L;
        if(param.get("po_id")!=null&&!param.get("po_id").equals("")){
            po_id = Long.valueOf(param.get("po_id"));
        }
        System.out.println(po_id);
        String jur_title = null;
        if(param.get("jur_title")!=null&&!param.get("jur_title").equals("")){
            jur_title = param.get("jur_title");
        }
        return R.ok().message("查询权限信息成功").data("list",jurisdictionService.jurisdictionlist(po_id,jur_title));
    }






    @PostMapping("/jurisdictionlisttwo")
    @Log(title = "查询角色权限id", operationType = OperationType.SELECT)
    public R jurisdictionlisttwo(@RequestBody Map<String,String> param) {
        Long po_id  = Long.valueOf(param.get("po_id"));
        return R.ok().message("查询角色权限id成功").data("list",jurisdictionService.jurisdictionlisttwo(po_id));
    }













    /**
     * 管理员登录
     * @param adminLoginRequest
     * @return
     */
    @PostMapping("/login")
    public ServerResponse adminLogin(@RequestBody UserLoginRequest adminLoginRequest) {
        Map<String, Object> map = new HashMap();
        Admin admin = adminService.adminLogin(adminLoginRequest.getUsername(), adminLoginRequest.getPassword());
        if (admin != null){
            String token = tokenService.getToken(admin);
            map.put("admin", admin);
            map.put("token", token);
            return ServerResponse.ofSuccess(map);
        }
        return ServerResponse.ofError("用户名或密码错误!");
    }



    /**
     * 密码修改
     * @return
     */
    @PostMapping(path = "userupdatepassword")
    @Log(title = "密码修改", operationType = OperationType.UPDATE)
    public R userupdatepassword(@RequestBody Map<String,String> param) throws Exception {
        Long user_id = Long.valueOf(param.get("user_id"));
        String oldpassword = param.get("oldpassword");
        String newpassword = param.get("newpassword");
        if(adminService.yanzheng(user_id,oldpassword)!=0){

            boolean a = adminService.passwordupd(user_id,newpassword);
            if (a){
                return R.ok().message("密码修改成功");
            }else {
                throw new MZException(CodeEnum.PASS_UPD);
            }
        }else {
            throw new MZException(CodeEnum.PASS_ERROE);
        }
    }




    /**
     * 管理员登录
     * @param param
     * @return
     */
    @PostMapping("/logintext")
   /* @Log(title = "登录", operationType = OperationType.LOGIN)*/
    public R adminLogin(@RequestBody  Map<String,String> param) {
        //获取账号
        String account = param.get("username");
        //输出账号测试
        System.out.println(account);
        //获取密码
        String password = param.get("password");
            //查询人员账号是否存在，不存在则抛出账号不存在
            if (adminService.selectaccount(account) == null) {
                throw new MZException(CodeEnum.USER_lOGIN_PHONE);
                //查询人员密码是否正确，不正确则抛出密码不正确
            } else if (adminService.selectpassword(account, password) == null) {
                throw new MZException(CodeEnum.USER_lOGIN_PASSWORD);
                //如果都存在则正常登录
            } else {
             AdminDto adminDto =  adminService.login(account, password);
             return R.ok()
                 /*    .data("token",adminDto.getToken())*/
                     .data("list",adminDto)
                     .message("登录成功！！");
            }
    }


    /**
     * 管理员更新个人资料
     * @return
     */
    @PostMapping("/modify")
    @Log(title = "管理员更新个人资料", operationType = OperationType.UPDATE)
    public ServerResponse modifyAdmin(@RequestBody Admin admin) {

        return adminService.updateById(admin) ? ServerResponse.ofSuccess("更新成功！") : ServerResponse.ofError("更新失败！");
    }


    /**
     * 根据ID查询管理员信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Log(title = "根据ID查询管理员信息", operationType = OperationType.SELECT)
    public ServerResponse queryAdmin(@PathVariable("id") Integer id) {
        return ServerResponse.ofSuccess(adminService.getById(id));
    }


    /**
     * 管理员修改密码
     * @param passwordVO
     * @return
     */
    @PostMapping("/password")
    @Log(title = "管理员修改密码", operationType = OperationType.UPDATE)
    public ServerResponse updatePass(@RequestBody PasswordVO passwordVO) {
        System.out.println(passwordVO + "======");
        QueryWrapper<Admin> wrapper = new QueryWrapper();
        wrapper.eq("id", passwordVO.getId());
        wrapper.eq("password", passwordVO.getOldPass());
        Admin admin = adminService.getOne(wrapper);
        if (admin == null) {
            return ServerResponse.ofError("旧密码错误");
        }
        // 否则进入修改密码流程
        admin.setPassword(passwordVO.getNewPass());
        boolean b = adminService.updateById(admin);
        if (b) {
            return ServerResponse.ofSuccess("密码修改成功");
        }
        return ServerResponse.ofError("密码更新失败");
    }








    /**
     * 设置用户角色
     * @param
     * @return
     * @throws MZException
     */
    @PostMapping(path = "/useraddpost")
    @Log(title = "设置用户角色", operationType = OperationType.OTHER)
    public R useraddpost(@RequestBody Map<String,String> param/*, HttpServletRequest request*/)throws MZException{
        // 获取请求消息中的所有头字段
        /*     String  token  = request.getHeader("token");*/
        //先把这个角色的权限删了直接
        Long user_id  = Long.valueOf(param.get("user_id"));
        userAsPostService.deleteByUserId(user_id);
        //然后从新设置，多简单啊，侯浩然不会？
        if (param.get("po_id")!=null&&!param.get("po_id").equals("")){
            String list = param.get("po_id");
            int flag = 0;
            String[] m = list.split(",");
            for (int i = 0; i < m.length; i++) {
                flag = userAsPostService.insertByuserIdandpostId( user_id, Long.valueOf(m[i]));
            }
            if (flag<=0) {
                throw new MZException(CodeEnum.POST_ADD_JUR);
            }
        }
        return R.ok().message("用户设置角色成功");
    }





    /**
     * 设置角色权限
     * @param
     * @return
     * @throws MZException
     */
    @PostMapping(path = "/postaddjur")
    @Log(title = "设置角色权限", operationType = OperationType.OTHER)
    public R postaddjur(@RequestBody Map<String,String> param/*, HttpServletRequest request*/)throws MZException{
        // 获取请求消息中的所有头字段
        /*     String  token  = request.getHeader("token");*/
        //先把这个角色的权限删了直接
        Long po_id  = Long.valueOf(param.get("po_id"));
        postAsJurisdictionService.deleteByPoId(po_id);
        //然后从新设置，多简单啊，侯浩然不会？
        if (param.get("jur_id")!=null&&!param.get("jur_id").equals("")){
            String list = param.get("jur_id");
            int flag = 0;
            String[] m = list.split(",");
            for (int i = 0; i < m.length; i++) {
                flag = postAsJurisdictionService.insertBypoIdandjurId( po_id, Long.valueOf(m[i]));
            }
            if (flag<=0) {
                throw new MZException(CodeEnum.POST_ADD_JUR);
            }
        }
        return R.ok().message("角色设置权限成功");
    }
}

